import React, { Component } from 'react';
import {
	StyleSheet, Image, TouchableOpacity, TextInput,
	Text, View, Dimensions, PixelRatio, Alert, FlatList, KeyboardAvoidingView, Platform, ScrollView,
} from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { SearchInput } from '../../../component/SearchInput.js';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { StateLightBox } from '../../../component/Store';
import QuoteService from './_common/service.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import MethodUtil from '../../../utils/MethodUtil';
import ToastUtil from '../../../utils/toast';
import moment from 'moment';
import DatePicker from 'react-native-datepicker';
import { SlideSelect } from '../../../components/common/slideSelect';

const searchLeft = require('../../../imgs/customer/searchLeft.png');
const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;

export class ToQuotePage extends Component {
	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		return {
			headerTitle: (<SearchInput
				inputLeftIcon={searchLeft}
				setKeyWord={(txt) => { params.setKeyWord(txt); }}
				onChangeText={() => { params.doSearch(); }}
				onSubmitEditing={() => { params.editing() }}
				onBlurFn={() => { params.editing() }}
				placeholder={'请输入商品名称/MDM码'}
			/>),
			headerTintColor: style.color.white,//
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color="#fff" />,
			headerRight: (
				<Text onPress={() => { params.editing() }} style={[style.headTow.headerRight, { color: '#fff' }]}>搜索</Text>
			),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: style.head.headerTitleStyle
		}
	};

	constructor(props) {
		super(props);
		const { choice } = props.navigation.state.params || {};
		//筛选-地区数据
		this.areaData = [];
		//筛选-状态数据
		this.stateData = [
			{ id: 'WAIT_SUBMIT', title: '待提报' },
			//{ id: 'WAIT_AUDITING', title: '待审批' },
			{ id: 'AUDITING', title: '审批中' },
			{ id: 'AUDIT_UNPASS', title: '审批驳回' }
		]
		this.state = {
			modalVisible: false,
			stateIndex: 0, // 状态index选中索引
			areaIndex: 0, // 地区index选中索引
			stateTitle: this.stateData[0].title,
			areaTitle: '',  // 地区标题
			areaTitleNew: '',
			areaTitleOld: '',
			branchIdOld: '',
			branchIdNew: false,
			tabIndex: 0,
			modeIndex: 0,
			refuseModalVisible: false,   // 备注弹框显示隐藏
			modalRemark: false, // 备注弹框展示
			stateLightBoxData: false, // 审批状态显示
			isLoadIco: false,  // 下拉涮新的 图标
			status: 'loading',
			allNun: 0, // 选中个数
			alertShow: false,
			options: [],
			choice: choice || {},
		}
		this.selcet = false;
		this.sendData = {   // 传参数
			searchKey: null, // 关键词
			startDate: moment().subtract(1, 'month').format('YYYY-MM-DD'),
			startTime: moment().subtract(1, 'month').format('YYYY-MM-DD'),
			endDate: moment().format('YYYY-MM-DD'),
			endTime: moment().format('YYYY-MM-DD'),
			status: this.stateData[0].id,  //状态
			branchId: '', // 地区
			startItemDate: moment().subtract().format('YYYY-MM-DD'),
			endItemDate: moment().format('YYYY-MM-DD'),
		}
		this.stateLightBoxData = {
			onClosePress: this._closeLightBox,
			modalVisible: false,
			title: '审批状态',
			rowDataList: [],

		};
		this.pageNo = 1;//当前第几页
		this.totalPage = 0; //总页数
		this.removeArr = [];  // 删除参数
		this.cancelArr = []; // 撤回参数
		this.allList = []; // 批量提交参数

	}


	async componentWillMount () {
		//查询用户授权机构
		let dictionaryData = await QuoteService.findSq() || [];
		dictionaryData.forEach(element => {
			this.areaData.push({ dictKey: element.organCode, title: element.organName })
		});

		//获取用户信息
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		if (userInfo) {
			userInfo = JSON.parse(userInfo);
		}
		this.sendData.branchId = userInfo.organId;
		this.userId = userInfo.userId;
		this.branchIdArr = userInfo.userOrganIds && userInfo.userOrganIds.split(',') || [];
		let lsModeIndex = 0;
		this.areaData.forEach((item, index) => {
			if (userInfo.organId == item.dictKey) {
				lsModeIndex = index;
			}
			console.log('item', item)
		})

		this.setState({
			areaTitle: userInfo.organName,
			areaTitleOld: userInfo.organName,  // 存  old 
			areaTitleNew: this.areaData[lsModeIndex].title,
			branchIdNew: this.areaData[lsModeIndex].dictKey,
			branchIdOld: userInfo.organId,
			modeIndex: lsModeIndex,
			areaIndex: lsModeIndex,
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
		//获取
		this._getData(true);
	}

	componentDidMount () {
		this.props.navigation.setParams({
			setKeyWord: this._setKeyWord,
			doSearch: this._doSearch,
			editing: this._editing
		});
	}

	async componentWillUnmount () {

	}

	_getData = async (refreshOff) => {

		let { tabIndex, choice } = this.state;
		let responseData = [];

		if (refreshOff) {
			this.allList = [];
			this.removeArr = [];
			this.removeArr = [];
			this.setState({
				status: 'loading',
				allNun: this.allList.length
			});
		}
		this.sendData.corpId = choice.corpId;
		if (tabIndex == '0') {
			if (this.selcet) {
				this.sendData.startDate = this.sendData.startTime;
				this.sendData.endDate = this.sendData.endTime;
			} else {
				this.sendData.startDate = moment().subtract(1, 'month').format('YYYY-MM-DD');
				this.sendData.endDate = moment().subtract().format('YYYY-MM-DD');
			}
		} else {
			if (this.selcet) {
				this.sendData.startDate = this.sendData.startItemDate;
				this.sendData.endDate = this.sendData.endItemDate;
			} else {
				this.sendData.endDate = this.sendData.endItemDate;
				this.sendData.startDate = this.sendData.startItemDate;
			}
		}
		if (!tabIndex) {
			responseData = await QuoteService.quoteList(this.sendData);
		} else {//生效
			responseData = await QuoteService.quoteListFinish(this.sendData);
		}

		//return
		if (responseData && responseData.rows && responseData.rows.length) {
			this.totalPage = responseData.totalPage;
			console.log('数据', responseData)
			// 添加图标标识
			responseData.rows && responseData.rows.map((element) => {
				element.checked = false;
				element.price = null;
				return element
			})

			if (refreshOff) { //刷新
				this.setState({
					status: 'data',
					isLoadIco: false,
					listData: responseData.rows,
				});
			} else { // 加载
				this.setState({
					status: 'data',
					isLoadIco: false,
					listData: this.state.listData.concat(responseData.rows),
				});
			}
		} else { //没数据
			this.setState({
				isLoadIco: false,
				status: 'empty',
				listData: []
			});
		}

	}



	//搜索value
	_setKeyWord = (txt) => {
		this.sendData.searchKey = txt;
	}
	//监听输入框变化
	_doSearch = () => {
		console.log('监听');
	}
	//提交编辑
	_editing = () => {
		this._getData(true)
	}

	// 点击哪个栏目
	_itemFn = (sendObj) => {
		let { modeType } = this.state;
		this._showVisible();
		if (modeType == 'STATE') {   // 状态
			this.sendData.status = sendObj.item.id;
			this.setState({
				stateIndex: sendObj.index,
				stateTitle: sendObj.item.title,
			})
		} else {  // 地区
			this.sendData.branchId = sendObj.item.dictKey;
			this.setState({
				areaIndex: sendObj.index,
				areaTitle: sendObj.item.title,
				areaTitleNew: sendObj.item.title,
				branchIdNew: sendObj.item.dictKey
			})
		}
		this.pageNo = 1;
		this._getData(true);
	}

	//点击显示隐藏
	_showVisible = () => {
		if (this.state.modalVisible) {
			this.setState({
				modalVisible: false
			})
		} else {
			this.setState({
				modalVisible: true
			})
		}
	}

	// 选择状态
	_selectFn = (data, index, type) => {
		this.setState({
			modelData: data,
			modeIndex: index,
			modeType: type
		})
		this._showVisible();
	}

	//tab切换
	_tabFn = (index) => {
		let { areaTitleNew, areaTitleOld, branchIdOld, branchIdNew, tabIndex, } = this.state;			// startItemDate: this.sendData.startDate,
		if (index == tabIndex) return;
		// if (!index) {   //tab1
		// 	this.sendData.branchId = branchIdOld;
		// 	this.setState({
		// 		tabIndex: index,
		// 		modalVisible: false,
		// 		areaTitle: areaTitleOld
		// 	}, () => {
		// 		this._getData(true);
		// 	})
		// } else {
		//}
		this.sendData.branchId = branchIdNew || branchIdOld;
		this.setState({
			tabIndex: index,
			modalVisible: false,
			areaTitle: areaTitleNew
		}, () => {
			this._getData(true);
		})
		//}
	}

	//弹出备注弹框
	_showMarkModel = (newPrice, goodsId, lastPrice, applyId, branchId) => {
		this.price = newPrice || lastPrice;
		this.goodsId = goodsId;
		this.lastPrice = lastPrice;
		this.applyId = applyId || null;
		this.branchId = branchId;
		this.setState({
			refuseModalVisible: true
		})
	}

	//点击提交按钮
	_commitFn = async (remark) => {
		this.setState({
			refuseModalVisible: false,
		});
		let params = {
			goodsId: this.goodsId,
			suggestedPrice: this.price,
			lastPrice: this.lastPrice,
			remark,
			applyId: this.applyId, // 1.审批驳回状态 2.提交报价 -> 清空
			branchId: this.branchId
		}
		let responseData = await QuoteService.quoteAdd(params);

		if (responseData) {
			ToastUtil.showSuccess('报价成功').then(() => {
				this._getData(true);
			});
		}
	}

	// 备注showdemo
	_retuenMarkModel = () => {
		let { markBody } = this.state;
		return (
			<View style={styles.markBox}>
				<Text style={styles.markTitle}>备注</Text>
				<ScrollView>
					<Text style={styles.markBody}>{markBody}</Text>
				</ScrollView>
			</View>
		)
	}

	//备注点击显示
	_showMark = (markBody) => {
		this.setState({
			modalRemark: true,
			markBody
		})
	}

	//关闭备注
	_closeMarkModel = () => {
		this.setState({
			modalRemark: false
		})
	}

	//撤回弹框
	_recallModel = (str, applyId) => {
		//if (this.allList.length) {
		Alert.alert('提示', `确定要${str}吗？`, [
			{
				text: '确认', onPress: () => {
					if (str == '删除') {
						this._removeFn(applyId);
					} else if (str == '撤回') {
						this._cancelFn(applyId)
					}
				}
			},
			{ text: '取消', onPress: () => { console.log('取消') } },
		]);
		// } else {
		// 	ToastUtil.showInfo('请先勾选');
		// }

	}

	//批量弹框
	_approveModel = (str) => {
		if (this.allList.length) {
			Alert.alert('提示', `确定要批量${str}吗？`, [
				{
					text: '确认', onPress: () => {
						if (str == '提交') {
							this._addAll();
						} else if (str == '删除') {
							this._removeFn();
						} else if (str == '撤回') {
							this._cancelFn();
						} else if (str == '报价') {
							this._addAll(true);
						}
					}
				},
				{ text: '取消', onPress: () => { console.log('取消') } },
			]);
		} else {
			ToastUtil.showInfo('请先勾选');
		}

	}

	//关闭审批状态弹框
	_closeLightBox = () => {
		this.stateLightBoxData.modalVisible = false;
		this.setState({
			ls: false
		});
	}

	//显示审批状态弹框
	_showLightBox = async (applyId, processInstanceId) => {
		let { tabIndex, choice } = this.state;
		let params = {
			bizId: applyId,
			bizObjType: 14,
			processInstanceId: processInstanceId,
			corpId: choice.corpId || null
		}

		this.setState({
			status: 'loading'
		});

		let responseData = await QuoteService.quoteStatus(params);
		this.stateLightBoxData.rowDataList = responseData;
		this.stateLightBoxData.modalVisible = true;


		this.setState({
			status: 'data'
		});
	}

	// 下拉更新函数
	_isLoadRefresh = async () => {
		this.pageNo = 1;
		await this._getData(true);
	}

	// 上拉更新函数
	_onEndReached = async () => {
		if (this.pageNo < this.totalPage) {
			this.pageNo++;
			this._getData();
		}
	}

	// 提报时间转化
	_returnTime = (returnTime) => {
		if (returnTime && returnTime.length) {
			returnTime = returnTime.split(' ')[0];
			returnTime = returnTime.split('-');
			returnTime = returnTime[1] + '月' + returnTime[2] + '日';
		}
		return returnTime || '';
	}

	// 点击选中
	_radiusFn = (itemData, staffId) => {
		let { tabIndex, branchIdOld } = this.state || {};
		if (!tabIndex && this.userId != itemData.staffId) return;
		if (tabIndex && branchIdOld != itemData.branchId) return;

		itemData.checked = !itemData.checked;
		if (itemData.checked) {
			this.removeArr.push(itemData.applyId);
			this.cancelArr.push(itemData.applyId);

			this.allList.push({
				goodsId: itemData.goodsId,
				lastPrice: itemData.suggestedPrice,
				applyId: itemData.applyId,
				suggestedPrice: itemData.price
			})

		} else {
			this.removeArr.map((element, index) => {
				if (element == itemData.applyId) {
					this.removeArr.splice(index, 1);
				}
			})
			this.cancelArr.map((element, index) => {
				if (element == itemData.applyId) {
					this.cancelArr.splice(index, 1);
				}
			})
			this.allList.map((element, index) => {
				if (element.goodsId == itemData.goodsId) {
					this.allList.splice(index, 1);
				}
			})
		}
		console.log('this.removeArr', this.removeArr);
		console.log('this.removeArr', this.cancelArr);
		console.log('this.allList', this.allList);
		this.setState({
			allNun: this.removeArr.length
		})
	}

	//最大值 昨天:1000 上次:1200 提报:1100
	_maxFn = (suggestedPrice, lastPrice, yesdayPrice) => {
		let range1 = MethodUtil.countObj.subtract(suggestedPrice || 0, lastPrice || 0);
		let range2 = MethodUtil.countObj.subtract(suggestedPrice || 0, yesdayPrice || 0);
		//相同值 取 跌
		if ((Math.abs(range1) == Math.abs(range2)) && (range1 != range2)) {
			return range1 > range2 ? range2 : range1;
		}
		return Math.abs(range1) > Math.abs(range2) ? range1 : range2;
	}


	_compare = (num1, num2) => {
		return MethodUtil.countObj.subtract(num1 || 0, num2 || 0);
	}

	_time = (createTime) => {
		let today = moment().format('YYYY-MM-DD');
		let result = false;
		createTime = createTime.split(' ')[0];
		if (createTime && (today == createTime)) {
			result = true;
		}
		return result;
	}

	//一条数据模板
	_renderItemView = (customer) => {
		let rightImg = require('../../../imgs/global/success.png');
		let emptyImg = require('../../../imgs/global/option.png');
		let { goodsName, staffName, bizTeamName, createTime, statusName, suggestedPrice, lastPrice, remark, prodDate,
			branchId, goodsId, applyId, staffId, checked, processInstanceId, price, organName, yesdayPrice } = customer.item || {};

		if (suggestedPrice) {
			suggestedPrice = suggestedPrice.toString() || '0';
		}

		let range1 = this._compare(suggestedPrice, lastPrice);
		let range2 = this._compare(suggestedPrice, yesdayPrice);
		let downImg = require('../../../imgs/my-siter/down.png');
		let upImg = require('../../../imgs/my-siter/up.png');

		let range = this._maxFn(suggestedPrice, lastPrice, yesdayPrice);
		let returnTime = this._returnTime(prodDate);
		let { tabIndex, branchIdOld } = this.state || {};
		let { status } = this.sendData;
		return (
			<View style={styles.listItem}>
				<View style={styles.timeView}>
					<Text style={styles.time}>{returnTime}</Text>
				</View>
				<View style={styles.listItemHead}>
					<TouchableOpacity style={styles.itemLeft} onPress={() => { this._radiusFn(customer.item) }}>
						{/* */
							!tabIndex && this.userId == staffId && this._time(prodDate) ? (<Image style={styles.bombImg} source={checked ? rightImg : emptyImg} />) : null
						}
						{/* */
							tabIndex && this._reseat(branchId) && this._time(prodDate) ? (<Image style={styles.bombImg} source={checked ? rightImg : emptyImg} />) : null
						}
						<Text style={styles.itemTitle} >{goodsName}</Text>
					</TouchableOpacity>
					<Text style={styles.itemRight}>{statusName}</Text>
				</View>

				<View style={styles.itemBody}>
					<View style={styles.itemMore}>
						<View style={[styles.itemMore, { width: '40%' }]}>
							<Text style={styles.itemFont}>昨日现货价：</Text>
							<Text style={[styles.itemFont, tabIndex == 0 ? styles.itemColor : styles.itemColorUp]}>
								{tabIndex == 0 ? yesdayPrice == null ? '-' : yesdayPrice : statusName == '审批通过' ? yesdayPrice == null ? '-' : yesdayPrice : '待审'}
							</Text>
						</View>

						<Text style={[styles.itemFont, styles.block]}>{tabIndex == 1 ? '当前较昨日涨跌' : '本次较昨日涨跌'}</Text>
						{tabIndex == 0 ? (
							<Image source={range2 >= 0 ? upImg : downImg} style={{ marginRight: 3 * scale, marginLeft: 10 * scale, height: 14 * scale }} />
						) :
							<View>
								{statusName == '审批通过' ? (
									<Image source={range2 >= 0 ? upImg : downImg} style={{ marginRight: 3 * scale, marginLeft: 10 * scale, height: 14 * scale }} />
								) : null
								}
							</View>
						}
						<Text style={[styles.itemFont, tabIndex == 0 ? range2 >= 0 ? styles.itemColorUp : styles.itemColorDown : styles.itemColorUp]}>
							{tabIndex == 0 ? range2 : statusName == '审批通过' ? range2 : ' -- '}
						</Text>
					</View>
					<View style={styles.itemMore}>
						<View style={[styles.itemMore, { width: '40%' }]}>
							<Text style={styles.itemFont}>{tabIndex == 1 ? '上次现货价' : '上次现货价(元)'}：</Text>
							<Text style={[styles.itemFont, tabIndex == 0 ? styles.itemColor : styles.itemColorUp]}>
								{tabIndex == 0 ? lastPrice == null ? '-' : lastPrice : statusName == '审批通过' ? lastPrice == null ? '-' : lastPrice : '待审'}
							</Text>
						</View>
						<Text style={[styles.itemFont, styles.block]}>{tabIndex == 1 ? '当前较上次涨跌' : '本次较上次涨跌'}</Text>
						{tabIndex == 0 ? (
							<Image source={range1 >= 0 ? upImg : downImg} style={{ marginRight: 3 * scale, marginLeft: 10 * scale, height: 14 * scale }} />
						) :
							<View>
								{statusName == '审批通过' ? (
									<Image source={range1 >= 0 ? upImg : downImg} style={{ marginRight: 3 * scale, marginLeft: 10 * scale, height: 14 * scale }} />
								) : null
								}
							</View>
						}
						<Text style={[styles.itemFont, tabIndex == 0 ? range1 >= 0 ? styles.itemColorUp : styles.itemColorDown : styles.itemColorUp]}>
							{tabIndex == 0 ? range1 : statusName == '审批通过' ? range1 : ' -- '}
						</Text>

					</View>
					<View style={styles.itemMore}>
						<Text style={styles.itemFont}>{tabIndex == 1 ? '当前现货价' : '本次提报价(元)'}：</Text>
						{
							(status != 'AUDITING' && this.userId == staffId) && tabIndex == 0 || (tabIndex == 0 && this._reseat(branchId)) ? (
								<TextInput
									keyboardType='numeric'
									returnKeyType='done'
									underlineColorAndroid='transparent'
									defaultValue={suggestedPrice}
									onChangeText={(valStr) => {
										customer.item.price = valStr;
										console.log('customer.item', customer.item)
									}}
									style={styles.inputBox} />
							) : (
									<View>
										{statusName == '审批通过' ? (
											<TextInput
												keyboardType='numeric'
												returnKeyType='done'
												underlineColorAndroid='transparent'
												defaultValue={suggestedPrice}
												onChangeText={(valStr) => {
													customer.item.price = valStr;
													console.log('customer.item', customer.item)
												}}
												style={styles.inputBox} />
										) : <Text style={[styles.itemFont, tabIndex == 0 ? styles.itemColorTheme : styles.itemColorUp]}>{tabIndex == 0 ? suggestedPrice : '待审'}</Text>


										}
									</View>

									// <Text style={[styles.itemFont, tabIndex == 0 ? styles.itemColorTheme : styles.itemColorUp]}>{tabIndex == 0 ? suggestedPrice : '待审'}</Text>
								)
						}
						{/* {
							(lastPrice || lastPrice == 0) ? (<View style={styles.lastPriceView}>
								<Text style={[styles.itemFont, range >= 0 ? styles.itemColorUp : styles.itemColorDown]}>{range > 0 ? range : Math.abs(range)}</Text>
								{range >= 0 ? <Image source={require('../../../imgs/my-siter/up.png')} /> : <Image source={require('../../../imgs/my-siter/down.png')} />}
							</View>) : null
						} */}

					</View>
					<View style={styles.itemMore}>
						<Text style={styles.itemFont}>提报时间：</Text>
						<Text style={[styles.itemFont, styles.itemColor]}>{createTime}</Text>
					</View>
					<View style={styles.itemMore}>
						<Text style={styles.itemFont}>提报部门：</Text>
						<Text style={[styles.itemFont, styles.itemColor]}>{organName || '-'}</Text>
					</View>
					<View style={styles.itemMore}>
						<Text style={styles.itemFont}>产品组：</Text>
						<Text style={[styles.itemFont, styles.itemColor]}>{bizTeamName || '-'}</Text>
					</View>
					<View style={styles.itemMore}>
						<Text style={styles.itemFont}>提报人：</Text>
						<Text style={[styles.itemFont, styles.itemColor]}><Text style={[styles.itemFont, styles.itemColor]}>{staffName || '--'}</Text></Text>
						{remark ? <TouchableOpacity style={[styles.itemMore, styles.remarkBox]} onPress={() => { remark && this._showMark(remark) }}>
							<Text style={[styles.remark]}>备</Text>
						</TouchableOpacity> : null}
					</View>
				</View>

				<View style={styles.itemBottom}>
					<View style={styles.itemMore}>
						{processInstanceId && (status == 'AUDITING' || status == 'AUDIT_UNPASS') ? <TouchableOpacity onPress={() => { this._showLightBox(applyId, processInstanceId) }} style={[styles.remarkBox]}><Text style={{ fontSize: 13 * scale, color: style.color.themeColor }}>[审批流]</Text></TouchableOpacity> : null}
					</View>
					{
						!tabIndex ? (
							<View style={styles.commitBox}>
								{status == 'WAIT_SUBMIT' && this.userId == staffId ? (
									<TouchableOpacity style={styles.commitItem} onPress={() => { this._recallModel('删除', applyId); }}>
										<Text style={styles.commitItemText}>删除</Text>
									</TouchableOpacity>
								) : null}

								{status != 'AUDITING' && this.userId == staffId && this._time(prodDate) ? (
									<TouchableOpacity style={[styles.commitItem, styles.commitItemActive]} onPress={() => { this._showMarkModel(customer.item.price, goodsId, suggestedPrice, applyId, branchId) }}>
										<Text style={[styles.commitItemText, styles.commitItemTextActive]}>提交</Text>
									</TouchableOpacity>
								) : null}

								{status == 'AUDITING' && this.userId == staffId ? (
									<TouchableOpacity style={[styles.commitItem, styles.commitItemActive]} onPress={() => { this._recallModel('撤回', applyId); }}>
										<Text style={[styles.commitItemText, styles.commitItemTextActive]}>撤回</Text>
									</TouchableOpacity>
								) : null}
							</View>
						) : (
								<View style={styles.commitBox}>
									<TouchableOpacity style={styles.commitItem} onPress={() => { this.props.navigation.navigate('HistoryListPage', { branchId, goodsId }) }}>
										<Text style={styles.commitItemText}>报价历史</Text>
									</TouchableOpacity>

									{this._reseat(branchId) && this.state.choice && this._time(prodDate) ? (
										<TouchableOpacity style={[styles.commitItem, styles.commitItemActive]} onPress={() => { this._showMarkModel(customer.item.price, goodsId, suggestedPrice, null, branchId) }}>
											<Text style={[styles.commitItemText, styles.commitItemTextActive]}>报价</Text>
										</TouchableOpacity>
									) : null}
								</View>
							)
					}

				</View>

			</View>
		)
	}

	_reseat = (branchId) => {
		branchId = `'${branchId}'`;
		let resealt = false;
		this.branchIdArr && this.branchIdArr.forEach((item) => {
			if (branchId == item) {
				resealt = true;
			}
		})
		return resealt;
	}
	//批量提交
	_addAll = async (onoff) => {
		let sendArr = [];
		this.state.listData.forEach((element) => {
			if (element.checked) {
				sendArr.push({
					goodsId: element.goodsId,
					lastPrice: element.suggestedPrice,
					applyId: element.applyId,
					suggestedPrice: element.price || element.suggestedPrice,
					branchId: element.branchId
				})
			}
		})
		if (onoff) {
			this.allList && this.allList.map((element) => {
				element.applyId = null;
				return element;
			})
		}
		let responseData = await QuoteService.quoteAddAll({ applyList: sendArr || [] });
		if (responseData) {
			ToastUtil.showSuccess(responseData).then(() => {
				this._getData(true);
			});
		}
	}

	// 删除报价
	_removeFn = async (sendData) => {
		if (sendData) {
			this.removeArr = [];
			this.removeArr.push(sendData);
		}
		let params = {
			applyIds: this.removeArr
		}
		let responseData = await QuoteService.quoteRemove(params);

		if (responseData) {
			ToastUtil.showSuccess('删除成功').then(() => {
				this._getData(true);
				this.removeArr = [];
			});
		}
	}

	//撤消
	_cancelFn = async (sendData) => {
		if (sendData) {
			this.cancelArr = [];
			this.cancelArr.push(sendData);
		}
		let params = {
			applyIds: this.cancelArr
		}
		let responseData = await QuoteService.quoteCancel(params);
		console.log('responseData', responseData)
		if (responseData) {
			ToastUtil.showSuccess('撤回成功').then(() => {
				this._getData(true);
				this.cancelArr = [];
			});
		}
	}



	//设置时间
	_setTimeCallback = (date, onoff) => {
		let { tabIndex } = this.state
		if (onoff) {
			if (tabIndex == '0') {
				this.sendData.endTime = date;
			} else {
				this.sendData.endItemDate = date;
			}
		} else {
			if (tabIndex == '0') {
				this.sendData.startTime = date;
				this.selcet = true;
			} else {
				this.sendData.startItemDate = date;
			}
		}
		this._getData(true);
	}



	render () {

		let { areaIndex, stateIndex, modalVisible, stateTitle, tabIndex, areaTitle, modelData, modeIndex, refuseModalVisible,
			modalRemark, listData, isLoadIco, status, allNun, alertShow, choice, options } = this.state || {};
		let { startDate, endDate, startItemDate, endItemDate, startTime, endTime } = this.sendData;
		return (
			<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
				<View style={styles.container}>
					<View style={styles.headTab}>
						<TouchableOpacity onPress={() => { this._tabFn(0) }} style={[tabIndex == 0 ? styles.tabActive : null]}>
							<Text style={[styles.tabText]}>价格提报状态</Text>
						</TouchableOpacity>
						<TouchableOpacity onPress={() => { this._tabFn(1) }} style={[tabIndex == 1 ? styles.tabActive : null]}>
							<Text style={[styles.tabText]}>已生效报价</Text>
						</TouchableOpacity>
					</View>
					<View style={styles.com}>
						<View style={styles.screen}>
							<TouchableOpacity onPress={() => { this._selectFn(this.areaData, areaIndex, 'AREA') }} style={styles.screenItem}>
								<Text style={styles.screenFont}>{areaTitle && areaTitle.length > 7 ? areaTitle.substr(0, 7) + '...' : areaTitle || ''}</Text>
								<Image source={require('../../../imgs/global/down.png')} tintColor='#404040' />
							</TouchableOpacity>
							{
								tabIndex ? null : (<TouchableOpacity onPress={() => { this._selectFn(this.stateData, stateIndex, 'STATE') }} style={[styles.screenItem, { width: 85 * scale }]}><Text style={styles.screenFont}>{stateTitle || ''}</Text>
									<Image source={require('../../../imgs/global/down.png')} tintColor='#404040' /></TouchableOpacity>)
							}
							<View style={styles.timeOutBox}>
								<View style={styles.timeBox}>
									<Text style={styles.timeText}>{tabIndex == '0' ? startTime : startItemDate}</Text>
									<DatePicker
										style={styles.fromTime}
										date={tabIndex == '0' ? startTime : startItemDate}
										mode="date"
										format="YYYY-MM-DD"
										minDate="1900-1-1"
										maxDate={tabIndex == '0' ? endTime : endItemDate}
										confirmBtnText="确认"
										cancelBtnText="取消"
										customStyles={{
											dateIcon: {
												opacity: 0,
												width: 0
											},
											dateInput: {
												borderWidth: 0
											}
										}}
										onDateChange={(date) => { this._setTimeCallback(date); }}
									/>
								</View>
								<Text>至</Text>
								<View style={styles.timeBox}>
									<Text style={styles.timeText}>{tabIndex == '0' ? endTime : endItemDate}</Text>
									<DatePicker
										style={styles.fromTime}
										date={tabIndex == '0' ? endTime : endItemDate}
										mode="date"
										format="YYYY-MM-DD"
										minDate={tabIndex == '0' ? startTime : startItemDate}
										maxDate={new Date()}
										confirmBtnText="确认"
										cancelBtnText="取消"
										customStyles={{
											dateIcon: {
												opacity: 0,
												width: 0
											},
											dateInput: {
												borderWidth: 0
											}
										}}
										onDateChange={(date) => { this._setTimeCallback(date, true); }}
									/>
								</View>
								<Image source={require('../../../imgs/global/down.png')} tintColor='#404040' />
							</View>

						</View>
						<View style={styles.list}>

							{
								status == 'loading' || status == 'empty' ? (
									<View style={{ height: '100%', width: '100%', position: 'absolute', zIndex: 1 }}><PageStatusIndex status={status} /></View>
								) : <View style={{ marginBottom: 54 * scale }}><FlatList
									data={listData}
									extraData={this.state}
									renderItem={this._renderItemView}
									refreshing={isLoadIco}
									onRefresh={this._isLoadRefresh}
									onEndReachedThreshold={0.5}
									onEndReached={this._onEndReached}
								/></View>
							}



							{
								listData && listData.length ? (
									<View style={styles.bottomBox}>
										<Text style={styles.bottomText}>批量：已选中<Text style={styles.bottomTextActive}>{allNun}</Text></Text>
										<View style={styles.bottomBoxNer}>
											{
												!tabIndex && this.sendData.status != 'AUDITING' ? (<View style={styles.removeBtnView}><Text style={styles.removeBtn} onPress={() => { this._approveModel('删除'); }}>删除</Text></View>) : null
											}
											{
												(!tabIndex && this.sendData.status == 'AUDITING') ? (<View style={styles.removeBtnView}><Text style={styles.removeBtn} onPress={() => { this._approveModel('撤回'); }}>撤回</Text></View>) : null
											}
											{
												!tabIndex && this.sendData.status != 'AUDITING' ? (<View style={styles.commitBtnView}><Text style={styles.commitBtn} onPress={() => { this._approveModel('提交'); }}>提交</Text></View>) : null
											}
											{
												tabIndex && this.state.choice ? (<View style={styles.commitBtnView}><Text style={styles.commitBtn} onPress={() => { this._approveModel('报价'); }}>报价</Text></View>) : null
											}
										</View>
									</View>
								) : null
							}
						</View>

					</View>
					{modalVisible ? (<Common styleBox={styles.modelBox} styleOut={styles.modelOut} data={modelData} itemFn={this._itemFn} imgIndex={modeIndex} allClick={this._showVisible} type="selectModal" />) : null}
					{modalRemark ? (<Common type="modal" demoData={this._retuenMarkModel()} modelClick={this._closeMarkModel} closeCallballFn={this._closeMarkModel} />) : null}
					<StateLightBox  {...this.stateLightBoxData} textStyle={{ marginLeft: 15 * scale, marginRight: 5 * scale }} />
					<RefuseModal visible={refuseModalVisible}
						placeholderText={'限定1000字…'}
						maxLength={1000}
						titleText={'备注'}
						btnPress={(remark) => {
							this._commitFn(remark);
						}}
						blurOnSubmit={"false"}
						bgPress={() => {
							this.setState({
								refuseModalVisible: false,
							});
						}} />
				</View >
				<SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this._isLoadRefresh();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</KeyboardAvoidingView>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		// backgroundColor: style.color.gray
		backgroundColor: '#EEF1FA',

	},
	headTab: {
		width: '100%',
		height: 40 * scale,
		flexDirection: 'row',
		justifyContent: 'space-around',
		alignItems: 'center',
		backgroundColor: style.color.themeColor
	},
	tabText: {
		color: '#fff',
		fontSize: 12 * scale,
		marginBottom: 12 * scale
	},
	tabActive: {
		borderBottomWidth: 2 * scale,
		borderStyle: 'solid',
		borderBottomColor: style.color.white,
	},
	com: {
		flex: 1,
		borderTopLeftRadius: 5 * scale,
		borderTopRightRadius: 5 * scale,
		// backgroundColor: style.color.gray,
		backgroundColor: '#EEF1FA',

	},
	itemTitle: {
		fontSize: 14 * scale,
		color: style.color.inputLabelValue
	},
	screen: {
		height: 48 * scale,
		borderTopLeftRadius: 5 * scale,
		borderTopRightRadius: 5 * scale,
		backgroundColor: style.color.white,
		flexDirection: 'row',
		justifyContent: 'space-around'
	},
	screenItem: {
		height: 48 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		flexDirection: 'row',
		alignItems: 'center'
	},
	screenFont: {
		fontSize: 13 * scale,
		marginRight: 3 * scale
	},
	listItem: {
		backgroundColor: style.color.white,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		marginTop: 12 * scale
	},
	listItemHead: {
		height: 44 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	bombImg: {
		width: 14 * scale,
		height: 14 * scale,
		marginRight: 12 * scale
	},
	itemLeft: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	itemRight: {
		fontSize: 14 * scale,
		color: '#404040'
	},
	itemBody: {
		borderBottomColor: style.color.white,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale
	},
	timeView: {
		position: 'absolute',
		right: 0 * scale,
		top: 54 * scale,
		height: 24 * scale,
		width: 70 * scale,
		paddingLeft: 12 * scale,
		borderTopLeftRadius: 13 * scale,
		borderBottomLeftRadius: 13 * scale,
		backgroundColor: '#e2e9ff',
	},
	time: {
		lineHeight: 24 * scale,
		fontSize: 11 * scale,
	},
	itemFont: {
		fontSize: 12 * scale,
		color: style.color.darkGray
	},
	itemColor: {
		color: style.color.dark
	},
	itemColorTheme: {
		color: style.color.themeColor
	},
	itemColorUp: {
		color: '#FC5454',
		//marginLeft: 10 * scale,
		marginRight: 3 * scale,
		fontSize: 14 * scale
	},
	itemColorDown: {
		color: style.color.button,
		//marginLeft: 10 * scale,
		marginRight: 3 * scale,
		fontSize: 14 * scale
	},
	itemMore: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 6 * scale,
		paddingBottom: 6 * scale,
	},
	itemBottom: {
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.gray,
		height: 49 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	remarkBox: {
		padding: 4 * scale,
		marginRight: 10 * scale
	},
	remark: {
		width: 18 * scale,
		height: 18 * scale,
		fontSize: 13 * scale,
		color: style.color.white,
		backgroundColor: '#F6AC35',
		lineHeight: 18 * scale,
		textAlign: 'center',
		//borderRadius: 8 * scale,
		marginLeft: 4 * scale,
	},
	remarkBtn: {
		width: 18 * scale,
		height: 18 * scale,
		fontSize: 10 * scale,
		color: style.color.white,
		backgroundColor: style.color.themeColor,
		lineHeight: 18 * scale,
		textAlign: 'center',
		borderRadius: 8 * scale,
	},
	commitBox: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	commitItem: {
		width: 86 * scale,
		height: 30 * scale,
		borderRadius: 15 * scale,
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: style.color.normal,
		marginLeft: 5 * scale
	},
	commitItemText: {
		textAlign: 'center',
		lineHeight: 30 * scale,
		color: style.color.normal,
		fontSize: 14 * scale,
	},
	commitItemActive: {
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: style.color.themeColor
	},
	commitItemTextActive: {
		color: style.color.themeColor,
	},
	inputBox: {
		width: 195 * scale,
		height: 34 * scale,
		backgroundColor: '#EFF2F2',
		paddingVertical: 0,
		borderRadius: 4 * scale,
		fontSize: 16 * scale,
		color: style.color.extheme,
	},
	modelOut: { top: 88 * scale },
	modelBox: {
		borderTopWidth: 2 * scale,
		borderStyle: 'solid',
		borderTopColor: style.color.gray,
		//	height: '60%'
	},
	markBox: {
		width: 300 * scale,
		height: 260 * scale,
		backgroundColor: style.color.white,
		borderRadius: 13 * scale,
	},
	markTitle: {
		fontSize: 18 * scale,
		textAlign: 'center',
		color: style.color.dark,
		marginTop: 15 * scale
	},
	markBody: {
		fontSize: 12 * scale,
		lineHeight: 26 * scale,
		padding: 20 * scale
	},
	list: {
		flex: 1,
	},
	bottomBox: {
		height: 54 * scale,
		width: '100%',
		backgroundColor: style.color.white,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		position: 'absolute',
		bottom: 0
	},
	bottomBoxNer: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		alignItems: 'center'
	},
	bottomText: {
		fontSize: 14 * scale,
		paddingLeft: 15 * scale
	},
	bottomTextActive: {
		color: style.color.themeColor
	},
	removeBtnView: {
		width: 90 * scale,
		height: 34 * scale,
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 17 * scale,
		marginRight: 10 * scale
	},
	removeBtn: {
		lineHeight: 34 * scale,
		textAlign: 'center',
		fontSize: 16 * scale,
		color: style.color.themeColor,
	},
	commitBtnView: {
		width: 90 * scale,
		height: 34 * scale,
		backgroundColor: style.color.themeColor,
		borderRadius: 17 * scale,
		marginRight: 10 * scale
	},
	commitBtn: {
		lineHeight: 34 * scale,
		color: style.color.white,
		fontSize: 16 * scale,
		textAlign: 'center',
	},
	fromTime: { padding: 0, margin: 0, opacity: 0, position: 'absolute', top: 0, left: 0 },
	timeBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		width: 85 * scale,
		height: 48 * scale,
	},
	timeText: {
		fontSize: 13 * scale,
		textAlign: 'center'
	},
	timeOutBox: {
		height: 48 * scale,
		paddingRight: 12 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		//width: 170 * scale,
	},
	lastPriceView: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	block: {
		color: '#000'
	}

})